package com.example.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.example.common.entity.OperatingLog;
import com.example.common.support.ApiException;

import javax.persistence.Table;
import java.util.Date;

/**
 * @Author wxy
 * @Date 2021/1/27 18:54
 * @Version 1.0
 */
public final class EFUtils {

    private static final String ADD_EF_LOG = "表{%s}进行了增加,新增的数据JSON为: %s";
    private static final String EDIT_EF_LOG = "表{%s}进行了编辑,编辑前的数据JSON为: %s,编辑后的数据JSON为: %s";
    private static final String DEL_EF_LOG = "表{%s}进行了删除,删除的数据JSON为: %s";

    /**
     * @param uid 当前登录用户id
     * @param t   对象
     * @param <T> 泛型
     * @return 日志体
     */
    public static <T> OperatingLog addEFLog(Long uid, T t) {
        OperatingLog log = new OperatingLog();
        log.setId(IdUtils.generateId());
        log.setUid(uid);
        log.setOType(2);
        log.setOperatingTxt(EFLog(log.getOType(), t, null, null, t.getClass()));
        log.setCreateTime(new Date());
        return log;
    }

    /**
     * @param uid    当前登录用户id
     * @param before 编辑前对象
     * @param after  编辑后对象
     * @param <T>    泛型
     * @return 日志体
     */
    public static <T> OperatingLog editEFLog(Long uid, T before, T after) {
        OperatingLog log = new OperatingLog();
        log.setId(IdUtils.generateId());
        log.setUid(uid);
        log.setOType(3);
        log.setOperatingTxt(EFLog(log.getOType(), null, before, after, before.getClass()));
        log.setCreateTime(new Date());
        return log;
    }

    /**
     * @param uid 当前登录用户id
     * @param t   对象
     * @param <T> 泛型
     * @return 日志体
     */
    public static <T> OperatingLog delEFLog(Long uid, T t) {
        OperatingLog log = new OperatingLog();
        log.setId(IdUtils.generateId());
        log.setUid(uid);
        log.setOType(4);
        log.setOperatingTxt(EFLog(log.getOType(), t, null, null, t.getClass()));
        log.setCreateTime(new Date());
        return log;
    }

    @SuppressWarnings("unchecked")
    private static <T> String EFLog(Integer oType, T t, T before, T after, Class tClass) {
        String beforeJson = null == before ? null : JSONObject.toJSONString(before);
        String afterJson = null == after ? null : JSONObject.toJSONString(after);
        String json = null == t ? null : JSONObject.toJSONString(t);

        Table table = (Table) tClass.getAnnotation(Table.class);
        String tableName = table.name();

        String txt;
        switch (oType) {
            case 2:
                txt = String.format(ADD_EF_LOG, tableName, json);
                break;
            case 3:
                txt = String.format(EDIT_EF_LOG, tableName, beforeJson, afterJson);
                break;
            case 4:
                txt = String.format(DEL_EF_LOG, tableName, json);
                break;
            default:
                throw new ApiException(1, "暂不支持状态");
        }
        return txt;
    }
}
